package com.example.basic.web.service.common.impl;

import com.example.basic.exception.ServiceException;
import com.example.basic.web.service.common.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;

import static com.example.basic.utils.CheckUtil.notNull;


@Service
@Transactional
@Slf4j
public class FileServiceImpl implements FileService {

    @Value("${sysFile.static.url}")
    private String staticUrl;
    @Value("${sysFile.image.url}")
    private String imageUrl;
    @Value("${sysFile.avatar.url}")
    private String avatarUrl;
    @Resource
    private HttpServletRequest request;

    /**
     * 医疗机构logo上传 zq
     * @param file 上传的文件
     * @return
     */
    @Override
    public String fileUpload(MultipartFile file) throws IOException {
        notNull(file,"上传文件不能为空");

        //文件上传
        String url = fileUpload(imageUrl,file);
        if (url == null) {
            throw new ServiceException("文件上传失败");
        }
        return url;
    }

    /**
     * 头像上传
     * @param file 上传的文件
     * @return
     */
    @Override
    public String avatarUpload(MultipartFile file) {
        notNull(file,"上传文件不能为空");

        //文件上传
        String url = fileUpload(avatarUrl+request.getAttribute("userCode")+"/",file);
        if (url == null) {
            throw new ServiceException("文件上传失败");
        }
        return url;
    }

    /**
     * @create 文件上传
     * @param uploadPath 文件保存地址
     * @param file 上传的文件
     * @return
     */
    private String fileUpload(String uploadPath, MultipartFile file){
        log.info("正在上传");
        // 文件上传地址不能为空
        if (uploadPath == null || "".equals(uploadPath)) {
            throw new ServiceException("文件上传地址不能为空");
        }
        // 定义上传后的文件名称，用于返回
        String fileName = null;
        try {
            //获取文件字节数组
            byte [] bytes = file.getBytes();
            //获取原始文件名
            String fileRealName = file.getOriginalFilename();
            fileName = fileRealName;
            //创建一个目录对象
            File dir = new File(staticUrl + uploadPath );
            //判断目录是否存在
            if(!dir.exists()){
                //目录不存在，则先创建
                dir.mkdirs();
            }
            try {
                //将临时文件转存到指定位置
                InputStream inputStream = file.getInputStream();
                File newFile = new File(staticUrl + uploadPath  + fileName);
                //写入指定文件夹
                OutputStream outstream = new FileOutputStream(newFile);
                byte[] b = new byte[1024 * 200];//每次传输200k
                int n;
                while ((n = inputStream.read(b)) != -1) {
                    outstream.write(b, 0, n);
                }
                outstream.flush();
                outstream.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            log.info("上传成功！" + staticUrl + uploadPath  + fileName);
            return "/" + uploadPath  + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("文件上传过程中发生异常");
        }
    }
}

